package servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.KategorijaPovlastice;
import model.Mesto;
import model.Povlastica;
import model.Prevoznik;
import model.PutnaDuz;
import model.User;
import model.Util;
import model.Version;
import model.VrstaPrevoza;

import org.htmlparser.Parser;
import org.htmlparser.Tag;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.tags.OptionTag;
import org.htmlparser.tags.SelectTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import app.PMF;
import bots.GSPNS;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Transaction;

public class DataLoaderServlet extends HttpServlet {

	private static final long serialVersionUID = -7310304827588123988L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {

		/*HttpSession session = req.getSession(true);
		User user = (User) session.getAttribute("user");*/

		PrintWriter out = resp.getWriter();		

		String pUsers = req.getParameter("users");
		String pPlaces = req.getParameter("places");
		String pTripCats = req.getParameter("tripCats");
		String pBenCats = req.getParameter("benCats");
		String pTripLines = req.getParameter("tripLines");
		String pVersions = req.getParameter("versions");

		String pDeleteAll = req.getParameter("deleteAll");

		System.out.println("Users: " + pUsers);
		System.out.println("Places: " + pPlaces);
		System.out.println("tripCats: " + pTripCats);
		System.out.println("BenCats: " + pBenCats);

		//ako nije pristiglo nista da se cita, samo ispisujemo meni
		if(pUsers == null && pPlaces == null && pTripCats == null
				&& pTripLines == null && pVersions == null && pDeleteAll == null){
			out.println("<head>");
			out.println("</head>");
			out.println("<body>");
			out.println("Nema prosledjenih parametara");
			out.println("<br>");
			out.println("<br>");
			out.println("<a href=\"/loadData?users=true&places=true&tripCats=true&benCats=true&versions=true\"><b>Sve(sem putne duzi)!</b></a>");
			out.println("<br>");
			out.println("<br>");
			out.println("<br>");
			out.println("<a href=\"/loadData?users=true\">Ucitaj korisnike</a>");
			out.println("<br>");
			out.println("<a href=\"/loadData?places=true\">Ucitaj mesta</a>");
			out.println("<br>");
			out.println("<a href=\"/loadData?tripCats=true\">Ucitaj vrste prevoza</a>");
			out.println("<br>");
			out.println("<a href=\"/loadData?benCats=true\">Ucitaj kategorije povlastice</a>");
			out.println("<br>");
			out.println("<a href=\"/loadData?tripLines=true\">Ucitaj GPSPNS putne duzi i prevoznike</a>");
			out.println("<br>");
			out.println("<br>");
			out.println("<a href=\"/loadData?versions=true\">Ucitaj verzije za proste entite</a>");
			out.println("<br>");
			out.println("<a href=\"/loadData?deleteAll=true\">Obrisi bazu</a>");
			out.println("<br>");
			out.println("<br>");
			out.println("<a href=\"WebContent/logIn.jsp\">LogIn</a>");
			out.println("</body>");
			return;
		}

		if(pUsers != null && pUsers.equals("true")){

			System.out.println("Snimamo korisnike");

			PersistenceManager pm = PMF.get().getPersistenceManager();

			//prvi je admin(true)
			User k1 = new User("asd", "123", true);
			/*User k2 = new User("aaa", "111"); // Lasta
			User k3 = new User("zzz", "111");
			User k4 = new User("bbb", "111"); // SeverTrans*/
			
			pm.makePersistent(k1);
			
			/*pm.makePersistent(k2);
			pm.makePersistent(k3);
			pm.makePersistent(k4);*/

			pm.close();

			System.out.println(Util.getAllEntitiesFromTable(User.class));
		}
		out.println("START");
		out.println("Ucitavam podatke...");		

		//snimamo mesta
		if (pPlaces != null && pPlaces.equals("true")) {
			PersistenceManager pm = PMF.get().getPersistenceManager();

			try {
				System.out.println("\n\tUcitavamo pocetnu stranicu...");
				Parser parser = new Parser("http://gspns.rs/redvoznje.php?rv=rvm");
				System.out.println("\n\tStranica ucitana!");
				// parsiramo stranicu
				NodeList nl = parser.parse(new HasAttributeFilter("name",
				"linija[]"));
				Tag tag = (Tag) nl.elementAt(0);

				// izvlacimo gradove iz stranice
				SelectTag slGradovi = (SelectTag) tag;
				// System.out.println("Ukupno gradova: "+slGradovi.getChildCount());
				OptionTag otGradovi[] = slGradovi.getOptionTags();
				String[] gradovi = new String[otGradovi.length];

				for (int i = 0; i < otGradovi.length; i++) {
					gradovi[i] = otGradovi[i].getValue();
					System.out.println(gradovi[i]);
					pm.makePersistent(new Mesto(gradovi[i]));
				}
				// Novi Sad moramo da dodamo rucno jer, ga nema u listi
				pm.makePersistent(new Mesto("NOVI SAD"));
			} catch (ParserException e) {
				e.printStackTrace();
			}

			pm.close();
		}

		//snimamo putne duzi
		if (pTripCats != null && pTripCats.equals("true")) {
			
			System.out.println("Snimamo vrste prevoza..");
			PersistenceManager pm = PMF.get().getPersistenceManager();

			VrstaPrevoza voz = new VrstaPrevoza("Voz");
			VrstaPrevoza bus = new VrstaPrevoza("Bus");

			voz = pm.makePersistent(voz);
			pm.makePersistent(bus);

			pm.close();
		}
		//snimamo kategorije povlastice
		if (pBenCats != null && pBenCats.equals("true")) {
			
			System.out.println("Snimamo kategorije povlastice");
			
			PersistenceManager pm = PMF.get().getPersistenceManager();

			KategorijaPovlastice kat1 = new KategorijaPovlastice("Student");
			KategorijaPovlastice kat2 = new KategorijaPovlastice("Novinar");
			KategorijaPovlastice kat3 = new KategorijaPovlastice("Penzioner");

			pm.makePersistent(kat1);
			pm.makePersistent(kat2);
			pm.makePersistent(kat3);
			
			pm.close();

		}
		
		//snimamo podatke sa GSPNS
		if (pVersions != null && pVersions.equals("true")) {
			
			System.out.println("Snimamo verzije za proste entite");

			PersistenceManager pm = PMF.get().getPersistenceManager();
			
			Version vMesto = new Version(Mesto.class.getSimpleName(), 1);
			Version vKatPovl = new Version(KategorijaPovlastice.class.getSimpleName(), 1);
			Version vVrstaPrev = new Version(VrstaPrevoza.class.getSimpleName(), 1);
			
			
			pm.makePersistent(vMesto);
			pm.makePersistent(vKatPovl);
			pm.makePersistent(vVrstaPrev);
			
			pm.close();
		}
		
		//snimamo podatke sa GSPNS
		if (pTripLines != null && pTripLines.equals("true")) {
			
			//PersistenceManager pm = PMF.get().getPersistenceManager();
			
			System.out.println("Startujemo GSPNS..");
			GSPNS gspNS = new GSPNS();
			//List<PutnaDuz> podaci = 
				gspNS.procitajPodatke();
			//GSPNS.napraviPutnudDuz();
			
			System.out.println("Zavrseno");
			
			//pm.close();

		}
		
		if (pDeleteAll != null && pDeleteAll.equals("true")) {

			System.out.println("Brisemo bazu...");
			DatastoreService ds = DatastoreServiceFactory.getDatastoreService();

			for(PutnaDuz pd : Util.getAllEntitiesFromTable(PutnaDuz.class)){
				System.out.println("Brisemo putnu duz: " + pd + "...");
				Transaction tx = ds.beginTransaction();
				ds.delete(pd.getSifra());
				tx.commit();			
			}
			
			for(Prevoznik prev : Util.getAllEntitiesFromTable(Prevoznik.class)){
				System.out.println("Brisemo prevoznika: " + prev + "...");
				Transaction tx = ds.beginTransaction();
				ds.delete(prev.getSifra());
				tx.commit();			
			}
			
			for(VrstaPrevoza vp : Util.getAllEntitiesFromTable(VrstaPrevoza.class)){
				System.out.println("Brisemo vrstu prevoza: " + vp + "...");
				Transaction tx = ds.beginTransaction();
				ds.delete(vp.getSifra());
				tx.commit();			
			}
			
			for(Povlastica povl : Util.getAllEntitiesFromTable(Povlastica.class)){
				System.out.println("Brisemo povlasticu: " + povl + "...");
				Transaction tx = ds.beginTransaction();
				ds.delete(povl.getSifra());
				tx.commit();			
			}
			
			for(KategorijaPovlastice katPovl : Util.getAllEntitiesFromTable(KategorijaPovlastice.class)){
				System.out.println("Brisemo kategorijuPovlastice: " + katPovl + "...");
				Transaction tx = ds.beginTransaction();
				ds.delete(katPovl.getSifra());
				tx.commit();			
			}
			
			for(Mesto mesto : Util.getAllEntitiesFromTable(Mesto.class)){
				System.out.println("Brisemo mesto: " + mesto + "...");
				Transaction tx = ds.beginTransaction();
				ds.delete(mesto.getSifra());
				tx.commit();			
			}
			
			for(User user : Util.getAllEntitiesFromTable(User.class)){
				System.out.println("Brisemo korisnika: " + user + "...");
				Transaction tx = ds.beginTransaction();
				ds.delete(user.getSifra());
				tx.commit();			
			}
			
			for(Version version : Util.getAllEntitiesFromTable(Version.class)){
				System.out.println("Brisemo korisnika: " + version + "...");
				Transaction tx = ds.beginTransaction();
				ds.delete(version.getSifra());
				tx.commit();			
			}
			
			System.out.println("Baza obrisana!");
		}


		out.println("<END>");

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
		doPost(req, resp);
	}
}